<?php
apf_require_class('APF_Controller');
apf_require_class("Util_BaseUrls");
apf_require_class("Const_BaseInfo");
apf_require_class("Const_User");
apf_require_class("Bll_Hr_Department");
apf_require_class("Bll_Hr_Position");
apf_require_class("Bll_Hr_UserRelation");
apf_require_class("Bll_Hr_Job");
apf_require_class("Bll_Hr_User");
apf_require_class("Bll_Flow_Role");
apf_require_class("Const_Tip");
apf_require_class("Bll_Hr_Property");
apf_require_class("Util_MultiPage");
apf_require_class("Const_Flow");
apf_require_class("Bll_Hr_OutInterface");
abstract class HrAbstractController extends APF_Controller {

    /**
     * @var APF
     */
    protected $apf = NULL;

    /**
     * @var NHRequest
     */
    protected $request = NULL;

    /**
     * @var APF_Response
     */
    protected $response = NULL;

    public function __construct() {
        parent::__construct();
        $this->apf = APF::get_instance();
        $this->request = $this->apf->get_request();
        $this->response = $this->apf->get_response();
        $this->update_session();
        $this->is_logout();

    }
    /**
     * 写死验证权限
     * @param unknown_type $user_code
     */
    private function check_auth($user_code){
        $allow = $this->apf->get_config('hr_auth','auth');
        $role_list = $_SESSION['role_list'];
        $_SESSION['menulist'] = $this->apf->get_config('menu_list');
        //权限通过
        if(in_array($user_code, $allow) || !empty($role_list[Const_Flow::ROLE_HR])){
            //检测菜单权限,只有hr权限时
            if(!in_array($user_code, $allow) && !empty($role_list[Const_Flow::ROLE_HR])){
                $matches = $this->request->get_router_matches();
                $dir_list = explode('/',substr($matches[0],1));
                $current_nav = $dir_list[0];
                if(!empty($current_nav) && !in_array($current_nav,array('staffmanage','error'))){
                    $this->show_tips('ERROR_AUTH', Util_BaseUrls::build_base_url());
                }else{
                    $_SESSION['menulist'] = array('staffmanage'=>'员工管理');
                }
            }
            return true;
        }
        $this->show_tips('ERROR_AUTH', Util_BaseUrls::home_url());
    }
    private function  update_session(){
        $this->session_act();
        //suid 伪装登陆
        $params = $this->request->get_parameters();

        if(isset($_SESSION['user_id']) && $_SESSION['user_id'] !=''){
            if($_SERVER['REQUEST_URI'] =='/login/' || $_SERVER['REQUEST_URI'] =='/login'|| $_SERVER['REQUEST_URI'] =='/'){
                $url = "http://".$_SERVER['HTTP_HOST'].'/hr/';
                $this->response->redirect($url,false,false);
            }
            $_SESSION['role_list'] = $this->_get_role_list($_SESSION['user_id']);
            $this->check_auth($_SESSION['code']);
            $this->request->set_attribute('userinfo',$_SESSION);
        }else{
            //未登录跳转到登录页面
            if(!preg_match('/\/login\//',$_SERVER['REQUEST_URI'])){
                $lasturl = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
                $keep = '';
                if($lasturl) {
                    $keep = '?back='.base64_encode($lasturl);
                }
                $url = "http://".$_SERVER['HTTP_HOST'].'/login/'.$keep;
                $this->response->redirect($url,false,false);
            }
        }
    }
    /**
     * 获得角色列表
     * @param unknown_type $user_id
     * @return multitype:
     */
    private function _get_role_list($user_id){
        $return = array();
        $bll_role = new Bll_Flow_Role();
        $role_list = $bll_role->get_role_by_user_id($user_id);
        if(!$role_list){
            $return = array();
        }

        foreach($role_list as $row){
            $return[$row['role_type']][] = $row['city_id'];
        }
        //添加普通员工权限
        $return[Const_Flow::ROLE_STAFF][] = $_SESSION['work_city_id'];

        return $return;
    }
    public function session_act(){
        //TODO 其他操作
        session_name('anjuke-portal');
        session_cache_expire(1440);
        session_start();
    }

    public function get_user_info(){
        return $_SESSION;
    }

    public function get_user_id(){
        return $_SESSION['user_id'];
    }

    /**
     * 构造用户登陆数据
     */
    public function set_user_info($uid){
        $this->session_act();

        $bll = new Bll_Hr_OutInterface();
        $this->user_info = $bll->get_user_base_info($uid,1);
        if(!empty($this->user_info)){
            $_SESSION['user_id'] = $this->user_info['user_id'];
            $_SESSION['email'] = $this->user_info['office_mail'];
            $_SESSION['code'] = $this->user_info['user_code'];
            $_SESSION['user_code'] = $this->user_info['user_code'];
            $_SESSION['name'] = $this->user_info['user_name'];
            //$_SESSION['english_name'] =$user_info['english_name'];
            $_SESSION['department_id'] = $this->user_info['department_id'];
            $_SESSION['department_name'] = $this->user_info['department_name'];
            $_SESSION['enter_date'] = date('Y-m-d',strtotime($user_info['enter_date']));
            $_SESSION['city_name'] =  $this->user_info['city_name'];
            $_SESSION['work_city_id'] = $this->user_info['work_city_id'];
        }
    }

    /**
     * 退出登录
     */
    public function is_logout(){
        //TODO 销毁用户信息 跳转到登录页面
        if(isset($_GET['logout'])){
            $this->session_act();
            session_unset();
            session_destroy();
            $apf = APF::get_instance();
            $oauth = APF::get_instance()->get_config('oauth_info');
            if($oauth){
                $logout = $oauth['oauth_url'].'/logout.php?client_id='.$oauth['client_id'].'&client_secret='.$oauth['client_secret'];
                $this->apf->get_response()->redirect($logout,false,false);
            }else{
                $this->apf->get_response()->redirect('/login/',false,false);
            }
        }
    }
    /**
     *
     * @param int $status 0错误 1成功
     * @param unknown_type $res
     */
    public function json_encode($status,$res){
        $result = array(
            'errcode'=>$status
            );
        if($status){
            $result['data']=$res;
        }else{
            $result['msg']=$res;
        }
        echo json_encode($result);
        exit();
    }

    /**
     * 检测字符串长度（UTF-8）
     * @param str $str 需要检测的字符串
     * @param int $len 最大长度
     * @return boolean
     */
    public function check_strlen($str, $len){
        if(mb_strlen($str, 'UTF-8') <= $len){
            return true;
        }
        return false;
    }
    /**
     * 跳转到提示页面
     * @param int $status 状态，1：正确状态，0：错误状态
     * @param str $code 错误码，统一到tip.php内定义
     * @param str $next 跳转到哪个链接
     */
    protected function show_tips($code = 'ERROR_SYSTEM', $next='', $status = 0){
        $next = !empty($next)
            ? $next
            : ((!empty($_SERVER['HTTP_REFERER']) && !strpos($_SERVER['HTTP_REFERER'], 'ShowTips')) ? $_SERVER['HTTP_REFERER'] : '');

        $params = "?status=$status&code=$code";
        if($next){
            $params .= '&next='.base64_encode($next);
        }
        $url = Util_BaseUrls::build_jump_url($params);
        $this->response->redirect($url);
    }
    /**
     * 检测页面请求是否存在POST操作
     *
     * @return boolean
     */
    public function is_post_request() {
        if ('post' == strtolower($_SERVER['REQUEST_METHOD'])) {
            return true;
        }
        return false;
    }
}